<template>
  <div v-loading="loading" id="loginView" style="height: 100%; width: 100%">
    <div class="logo_div">
      <p>效果图共享平台</p>
    </div>
    <el-form ref="formRef" hide-required-asterisk class="login_form" :rules="rules" :model="ruleForm">
      <el-form-item hide-required-asterisk label="账号" prop="user">
        <el-input class="login_input" v-model="ruleForm.user" label="用户" prefix-icon="User" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input class="login_input" v-model="ruleForm.password" type="password" label="密码" prefix-icon="Lock" placeholder="请输入密码" />
      </el-form-item>
      <div class="login_button">
        <el-button style="width: 100%" type="primary" size="large" @click="doLogin(formRef)">登录</el-button>
      </div>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { login } from '@/api/user';
import { useUserStore } from '@/stores/userInfo';
import { setValue, getValue, STORAGE_KEY } from '@/utils/localStorage';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
interface RuleForm {
  user: string;
  password: string;
}
const router = useRouter();
const remanber_me = ref(true);
const ruleForm = reactive<RuleForm>({
  user: getValue(STORAGE_KEY.MY_USERCODE) || '',
  password: getValue(STORAGE_KEY.MY_PASSWORD) || '',
});
const formRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  user: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});
const loading = ref<boolean>(false);
const doLogin = (formEl: FormInstance | undefined) => {
  console.log(formEl);
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      login(ruleForm)
        .then((r) => {
          const store = useUserStore();
          store.set_online_user(r.Data![0]);
          if (remanber_me.value) {
            setValue(STORAGE_KEY.MY_USERCODE, ruleForm.user);
            setValue(STORAGE_KEY.MY_PASSWORD, ruleForm.password);
          }
          loading.value = false;
          router.push('/');
        })
        .catch((e) => {
          loading.value = false;
        });
    } else {
      ElMessage.error('请先输入账号密码');
    }
  });
};
</script>
<style scoped>
.logo_div {
  font-size: xx-large;
  text-align: center;
  padding: 20px;
  color: #546b95;
}
.login_form {
  padding: 10px;
  height: 300px;
  margin: auto;
  width: 300px;
}
.login_input {
  width: 400px;
}
.login_button {
  margin-top: 20px;
  width: 100%;
}
</style>
